﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using Flitter.Properties;
using Newtonsoft.Json;

namespace Flitter.Twitter
{
    static class TwitterFrontend
    {
        public static Statuses GetStatuses()
        {
            if (TwitterConstants.IsSearch(Settings.Default.TWITTER_URL))
            {
                return GetStatusesFromSearch();
            }
            else
            {
                return GetStatusesFromTimeline();
            }
        }

        public static users GetUsers()
        {
            if (TwitterConstants.IsSearch(Settings.Default.TWITTER_URL))
            {
                return GetUsersFromSearch();
            }
            else
            {
                return GetUsersFromTimeline();
            }
        }

        private static Statuses GetStatusesFromSearch()
        {
            Statuses retval = new Statuses();

            SearchTimeline t = JsonConvert.DeserializeObject<SearchTimeline>(GetJson());
            retval = t.toStatuses();

            return retval;
        }

        private static users GetUsersFromSearch()
        {
            users retval = new users();

            SearchTimeline t = JsonConvert.DeserializeObject<SearchTimeline>(GetJson());
            retval = t.toUsers();

            return retval;
        }

        private static users GetUsersFromTimeline()
        {
            users retval = null;

            List<StatusesStatus> t = JsonConvert.DeserializeObject<List<StatusesStatus>>(GetJson());

            return retval;
        }

        private static Statuses GetStatusesFromTimeline()
        {
            Statuses retval = new Statuses();

            List<StatusesStatus> t = JsonConvert.DeserializeObject<List<StatusesStatus>>(GetJson());
            retval.Items = t.ToArray();

            return retval;
        }

        private static string GetJson()
        {
            string retval = null;

            using (WebClient client = new WebClient())
            {
                using (StreamReader reader = new StreamReader(client.OpenRead(Settings.Default.TWITTER_URL), Encoding.UTF8))
                {
                    retval = reader.ReadToEnd();
                }

                client.Dispose();
            }

            return retval;
        }
    }
}
